package com.xydtech.ecard.merchant.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xydtech.common.annotation.Log;
import com.xydtech.common.core.controller.BaseController;
import com.xydtech.common.core.domain.AjaxResult;
import com.xydtech.common.core.page.TableDataInfo;
import com.xydtech.common.enums.BusinessType;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.merchant.domain.EcardMerchantPartInfo;
import com.xydtech.ecard.merchant.domain.EcardPersonInfo;
import com.xydtech.ecard.merchant.domain.EcardReleaseRecord;
import com.xydtech.ecard.merchant.service.IEcardMerchantPartInfoService;
import com.xydtech.ecard.merchant.service.IEcardPersonInfoService;
import com.xydtech.ecard.merchant.service.IEcardReleaseRecordService;
import com.xydtech.ecard.merchant.utils.MyExcelUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电子名片个人信息Controller
 *
 * @author yuzhiguo
 * @date 2024-09-02 下午1:22
 */
@Controller
@RequestMapping("/merchant/person")
public class EcardPersonInfoController extends BaseController
{
    private String prefix = "merchant";

    @Autowired
    private IEcardPersonInfoService ecardPersonInfoService;
    @Autowired
    private IEcardReleaseRecordService ecardReleaseRecordService;
    @Autowired
    private IEcardMerchantPartInfoService ecardMerchantPartInfoService;

    @RequiresPermissions("merchant:person:view")
    @GetMapping()
    public String person()
    {
        return prefix + "/person";
    }

    //跳转网格下个人列表
    @RequiresPermissions("merchant:person:view")
    @GetMapping("/{perAreaId}")
    public String enterprise(@PathVariable("perAreaId") String perAreaId, ModelMap mmap)
    {
        mmap.put("perAreaId", perAreaId);
        return prefix + "/person";
    }

    /**
     * 查询电子名片个人信息列表
     */
    @RequiresPermissions("merchant:person:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(EcardPersonInfo ecardPersonInfo)
    {
        String salt = getSalt();//盐值
        startPage();
        List<EcardPersonInfo> list = ecardPersonInfoService.selectEcardPersonInfoList(ecardPersonInfo, salt);
        return getDataTable(list);
    }

    /**
     * 导出电子名片个人信息列表
     */
    @RequiresPermissions("merchant:person:export")
    @GetMapping("/export/{dataParam}")
    @ResponseBody
    public void export(@PathVariable("dataParam") String dataParam, HttpServletResponse response)
    {
        String salt = getSalt();//盐值
        //处理查询条件
        EcardPersonInfo ecardPersonInfo = new EcardPersonInfo();
        JSONArray parsed = (JSONArray) JSONObject.parse(dataParam);
        String ids = "";
        Map<String, Object> paramMap = new HashMap<>();
        for (Object o : parsed) {
            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(o));
            if ("params[startDate]".equals(jsonObject.getString("name"))){
                paramMap.put("startDate",jsonObject.getString("value"));
            } else if ("params[endDate]".equals(jsonObject.getString("name"))){
                paramMap.put("endDate",jsonObject.getString("value"));
            } else if ("deptId".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setDeptId(jsonObject.getLong("value"));
            } else if ("userName".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setUserName(jsonObject.getString("value"));
            } else if ("perCustName".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setPerCustName(jsonObject.getString("value"));
            } else if ("sortTime".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setSortTime(jsonObject.getString("value"));
            } else if ("perType".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setPerType(jsonObject.getInteger("value"));
            } else if ("releaseSts".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setReleaseSts(jsonObject.getString("value"));
            } else if ("visitSts".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setVisitSts(jsonObject.getString("value"));
            } else if ("state".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setState(jsonObject.getInteger("value"));
            } else if ("perAreaId".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setPerAreaId(jsonObject.getLong("value"));
            } else if ("ids".equals(jsonObject.getString("name"))){
                ids = jsonObject.getString("value");
            } else if ("id".equals(jsonObject.getString("name"))){
                ecardPersonInfo.setId(jsonObject.getLong("value"));
            }
        }
        ecardPersonInfo.setParams(paramMap);//时间条件
        List<EcardPersonInfo> list = new ArrayList<>();
        if (ecardPersonInfo.getDeptId() == null){
            ecardPersonInfo.setDeptId(ShiroUtils.getSysUser().getDeptId());
        }
        //判断ids是否为空，不为空则导出选择的数据
        if (StringUtils.objIsNullOrEmpty(ids)){
            list = ecardPersonInfoService.selectEcardPersonInfoListByExport(ecardPersonInfo, salt);
        } else {
            ids = ids.replaceAll("\\[","").replaceAll("]","");
            list = ecardPersonInfoService.selectEcardPersonInfoByIds(ids, salt);
        }
        for (EcardPersonInfo personInfo : list) {
            //查询企业成员信息
            EcardMerchantPartInfo merchantPartInfo = new EcardMerchantPartInfo();
            merchantPartInfo.setMerchantId(personInfo.getId());
            merchantPartInfo.setMerchantType("1");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            List<EcardMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoListByExport(merchantPartInfo, salt);
            personInfo.setMerchantPartDetail(partInfoList);
        }
        MyExcelUtils.exportExcel(list,
                "电子名片个人信息",
                "电子名片个人",
                EcardPersonInfo.class,
                "电子名片个人信息文件" + System.currentTimeMillis() + ".xls", response);

    }


    /**
     * 选择转交的客户经理
     */
    @RequiresPermissions("merchant:person:handOver")
    @GetMapping("/handOver/{ids}")
    public String choiceUserByHand(@PathVariable("ids") String ids, ModelMap mmap) {
        mmap.put("ids", ids);
        mmap.put("merchantType", "1");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
        return prefix + "/choiceUser";
    }

    /**
     * 个人转交
     */
    @Log(title = "个人转交客户经理", businessType = BusinessType.UPDATE)
    @PostMapping("/allocation")
    @ResponseBody
    public AjaxResult allocation(Long registId,Long deptId, Long[] ids, Long userId) {
        /**查询机构*/
        //SysUser user = sysUserService.selectUserById(userId);
        if(registId == null){
            return AjaxResult.error("请选择移交人员！");
        }
        if(deptId == null){
            return AjaxResult.error("请选择移交的机构！");
        }
        //移交个人列表
        List<EcardPersonInfo> ecardPersonInfoList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardPersonInfo ecardPersonInfo = new EcardPersonInfo();
            ecardPersonInfo.setId(ids[i]);
            ecardPersonInfo.setManagementPersonnelId(registId);
            ecardPersonInfo.setDeptId(deptId);
            ecardPersonInfoList.add(ecardPersonInfo);
        }
        return toAjax(ecardPersonInfoService.allocationEcardPersonInfo(ecardPersonInfoList,registId, userId));
    }

    /**
     * 释放个人
     *
     * @author yuzhiguo
     * @date 2024/9/2 下午4:05
     */
    @RequiresPermissions("merchant:person:handOver")
    @Log(title = "释放个人", businessType = BusinessType.UPDATE)
    @PostMapping("/release")
    @ResponseBody
    public AjaxResult release(Long[] ids) {
        //释放个人列表
        List<EcardPersonInfo> ecardPersonInfoList = new ArrayList<>();
        Long userId = ShiroUtils.getSysUser().getUserId();
        //新增个人释放记录
        List<EcardReleaseRecord> ecardReleaseRecordList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardPersonInfo ecardPersonInfo = new EcardPersonInfo();
            ecardPersonInfo.setId(ids[i]);
            ecardPersonInfo.setManagementPersonnelId(null);
            ecardPersonInfoList.add(ecardPersonInfo);

            EcardPersonInfo personInfo = ecardPersonInfoService.selectEcardPersonInfoById(ids[i]);//查询企业信息
            //新增释放记录
            EcardReleaseRecord ecardReleaseRecord = new EcardReleaseRecord();
            ecardReleaseRecord.setReleaseId(userId);//释放人用户id
            ecardReleaseRecord.setMerchantId(ids[i]);//个人id
            ecardReleaseRecord.setBelongRegistId(personInfo.getManagementPersonnelId());//企业归属人注册id
            ecardReleaseRecord.setMerchantType("1");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            ecardReleaseRecordList.add(ecardReleaseRecord);
        }
        ecardReleaseRecordService.batchInsertEcardReleaseRecord(ecardReleaseRecordList);//批量新增释放记录
        int i = ecardPersonInfoService.batchReleaseEcardPersonInfo(ecardPersonInfoList);
        return toAjax(i);
    }

    /**
     * 启用/停用个人
     *
     * @author yuzhiguo
     * @date 2024/9/2 下午4:16
     */
    @RequiresPermissions("merchant:person:switchOver")
    @Log(title = "启用/停用个人", businessType = BusinessType.UPDATE)
    @PostMapping("/switchOver")
    @ResponseBody
    public AjaxResult switchOver(Long[] ids, Integer state) {
        //个人列表
        List<EcardPersonInfo> ecardPersonInfoList = new ArrayList<>();

        for (int i = 0; i < ids.length; i++) {
            //修改创建人id和创建人机构id
            EcardPersonInfo ecardPersonInfo = new EcardPersonInfo();
            ecardPersonInfo.setId(ids[i]);
            ecardPersonInfo.setState(state);
            ecardPersonInfoList.add(ecardPersonInfo);
        }
        int i = ecardPersonInfoService.batchSwitchOverEcardPersonInfo(ecardPersonInfoList);
        return toAjax(i);
    }

    /**
     * 新增电子名片个人信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存电子名片个人信息
     */
    @RequiresPermissions("merchant:person:add")
    @Log(title = "电子名片个人信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(EcardPersonInfo ecardPersonInfo)
    {
        String salt = getSalt();//盐值
        return toAjax(ecardPersonInfoService.insertEcardPersonInfo(ecardPersonInfo, salt));
    }

    /**
     * 修改电子名片个人信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        EcardPersonInfo ecardPersonInfo = ecardPersonInfoService.selectEcardPersonInfoById(id);
        mmap.put("ecardPersonInfo", ecardPersonInfo);
        return prefix + "/edit";
    }

    /**
     * 修改保存电子名片个人信息
     */
    @RequiresPermissions("merchant:person:edit")
    @Log(title = "电子名片个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(EcardPersonInfo ecardPersonInfo)
    {
        String salt = getSalt();//盐值
        return toAjax(ecardPersonInfoService.updateEcardPersonInfo(ecardPersonInfo, salt));
    }

    /**
     * 删除电子名片个人信息
     */
    @RequiresPermissions("merchant:person:remove")
    @Log(title = "电子名片个人信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ecardPersonInfoService.deleteEcardPersonInfoByIds(ids));
    }
}
